"""
Made by Wang Shiheng
CopyRight(C) From WangShiheng
All copyright(C) reserved
"""
# Author: WangShiheng
# Create Time:2022/06/03
# Package:

import os
from util.RunTime.RunTimeAnnotator import time_test


@time_test(100, is_print=True)
def _get_all_port_using() -> dict[str, list[dict[str, str]]]:
    with os.popen('netstat -aon') as p:
        res = p.read().split('\n')
    ports = {
        'TCP': [],
        'UDP': []
    }
    for line in res:
        temp = [i for i in line.split(' ') if i != '']

        # 如果是TCP协议
        if len(temp) == 5 and temp[0].upper() == 'TCP':
            lport = {
                'pid': temp[4],
                'port': temp[1].split(':')[-1],
                'address': temp[1].replace(':' + temp[1].split(':')[-1], ''),
                'state': temp[3],
                'foreign_addr': temp[2]
            }
            ports['TCP'].append(lport)

        # 如果是UDP协议
        elif len(temp) == 4 and temp[0].upper() == 'UDP':
            lport = {
                'pid': temp[3],
                'port': temp[1].split(':')[-1],
                'address': temp[1].replace(':' + temp[1].split(':')[-1], '')
            }
            ports['UDP'].append(lport)

    return ports
